/**
 * 
 */
package spatil.join;

import indexing.grid.Cell;
import indexing.grid.Grid;

import java.util.Iterator;
import java.util.Set;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import spatial.geometry.MyPolygon;

/**
 * @author Xiaohui
 * 
 */
public class GridTest extends TestCase {

	final static int gridSize = 4;
	final static int cellSize = 4;

	Grid mygrid;
	MyPolygon poly1;
	MyPolygon poly2;
	MyPolygon poly3;
	MyPolygon poly4;
	int poly2Size = 3;
	int poly3Size = 3;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mygrid = new Grid(gridSize, cellSize);
		poly1 = new MyPolygon();
		poly1.addPoint(1, 1);
		poly1.addPoint(2, 2);
		poly1.addPoint(3, 1);

		int[] xs = { 1, 5, 3 };
		int[] ys = { 1, 1, 3 };
		poly2 = new MyPolygon(2, xs, ys);
		
		int[]xs1 = {1, 2, 9};
		int[] ys1 = {1, 6, 1};
		poly3 = new MyPolygon(3, xs1, ys1);
		
		int[] xs2 = {0, 0, 4, 4};
		int[] ys2 = {0, 4, 4, 0};
		poly4 = new MyPolygon(10, xs2, ys2);
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		mygrid = null;
	}

	public void testGetCell() {
		Cell c1 = mygrid.getCell(0, 0);
		assertNotNull(c1);
		Cell c2 = mygrid.getCell(1, 0);
		assertNotNull(c2);
		// System.out.println(c3);
		Cell c4 = mygrid.getCell(3, 0);
		assertNotNull(c4);

		Cell c5 = mygrid.getCell(4, 0);
		// System.out.println(c5);
		assertNotNull(c5);

	}

	public void testPolyConstructor() {
		assertEquals(3, poly1.npoints);
		assertEquals(3, poly2.npoints);
//		System.out.println(poly1.toString());
	}

	public void testIntersection() {
		//occupy one cell
		Set<Cell> cells1 = mygrid.intersectedCells(poly1);
		assertEquals(1, cells1.size());
		Iterator<Cell> it = cells1.iterator();
		assertEquals(mygrid.getCell(0, 0), it.next());
		
		//occupy two cells
		Set<Cell> cells2 = mygrid.intersectedCells(poly2);
		assertEquals(2, cells2.size());
		Iterator<Cell> it2 = cells2.iterator();
		
		assertEquals(mygrid.getCell(0, 0), it2.next());
		assertEquals(mygrid.getCell(1, 0), it2.next());
		
		//occupy more than two cells
		Set<Cell> cells3 = mygrid.intersectedCells(poly3);
		assertEquals(5, cells3.size());
		assertTrue(cells3.contains(mygrid.getCell(0, 0)));
		assertTrue(cells3.contains(mygrid.getCell(1, 0)));
		assertTrue(cells3.contains(mygrid.getCell(0, 1)));
		assertTrue(cells3.contains(mygrid.getCell(2, 0)));
		assertTrue(cells3.contains(mygrid.getCell(1, 1)));
		
		//rectangle test
		Set<Cell> cells4 = mygrid.intersectedCells(poly4);
		System.out.println("cells size:"+cells4.size());
		System.out.println("poly: "+poly4.toString());
		System.out.println("cell: "+mygrid.getCell(0, 0));
		assertEquals(1, cells4.size());
		assertTrue(cells4.contains(mygrid.getCell(0, 0)));
		assertTrue(poly4.contains(mygrid.getCell(0, 0))); 
	}

	public static Test suite() {
		return new TestSuite(GridTest.class);
	}

}
